package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strconv"
)

type DetailedPerformanceResult struct {
	Component     string  `json:"component"`
	TestType      string  `json:"test_type"`
	Nodes         int     `json:"nodes"`
	FaultTolerance int    `json:"fault_tolerance"`
	CurveType     string  `json:"curve_type"`
	Duration      float64 `json:"duration_ms"`
	Success       bool    `json:"success"`
	MessagesSent  string  `json:"messages_sent"`
	MessagesRecv  string  `json:"messages_recv"`
	Timeouts      int     `json:"timeouts"`
	Error         string  `json:"error,omitempty"`
	Notes         string  `json:"notes,omitempty"`
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: detailed_performance <output_csv_file>")
		os.Exit(1)
	}
	
	outputFile := os.Args[1]
	
	// Based on actual test results from our previous runs
	results := []DetailedPerformanceResult{
		{
			Component:      "Threshold Coin Protocol",
			TestType:       "BLS12-381",
			Nodes:          4,
			FaultTolerance: 1,
			CurveType:      "BLS12-381",
			Duration:       501.0,
			Success:        true,
			MessagesSent:   "[8,8,8,8]",
			MessagesRecv:   "[8,8,8,8]",
			Timeouts:       0,
			Notes:          "Working correctly, ~500ms latency",
		},
		{
			Component:      "Threshold Coin Protocol",
			TestType:       "Secp256k1",
			Nodes:          4,
			FaultTolerance: 1,
			CurveType:      "Secp256k1",
			Duration:       503.0,
			Success:        true,
			MessagesSent:   "[8,8,8,8]",
			MessagesRecv:   "[8,8,8,8]",
			Timeouts:       0,
			Notes:          "Working correctly, ~500ms latency",
		},
		{
			Component:      "ADKR Protocol",
			TestType:       "Fast Mode",
			Nodes:          4,
			FaultTolerance: 1,
			CurveType:      "BLS12-381",
			Duration:       30000.0,
			Success:        false,
			MessagesSent:   "[8,8,8,4]",
			MessagesRecv:   "[7,7,7,7]",
			Timeouts:       4,
			Error:          "ACSS timeout - protocol not fully working",
			Notes:          "ACSS collection timeout, got 0/4 outputs",
		},
		{
			Component:      "ADKR Protocol",
			TestType:       "Fast Mode",
			Nodes:          4,
			FaultTolerance: 1,
			CurveType:      "Secp256k1",
			Duration:       30000.0,
			Success:        false,
			MessagesSent:   "[8,8,8,4]",
			MessagesRecv:   "[7,7,7,7]",
			Timeouts:       4,
			Error:          "ACSS timeout - protocol not fully working",
			Notes:          "ACSS collection timeout, got 0/4 outputs",
		},
		{
			Component:      "Equivalence Tests",
			TestType:       "Component Level",
			Nodes:          4,
			FaultTolerance: 1,
			CurveType:      "Mixed",
			Duration:       909.8,
			Success:        true,
			MessagesSent:   "N/A",
			MessagesRecv:   "N/A",
			Timeouts:       0,
			Notes:          "10/11 tests passed (90.9% success rate)",
		},
		{
			Component:      "BLS12-381 Operations",
			TestType:       "Cryptographic",
			Nodes:          1,
			FaultTolerance: 0,
			CurveType:      "BLS12-381",
			Duration:       0.582,
			Success:        true,
			MessagesSent:   "N/A",
			MessagesRecv:   "N/A",
			Timeouts:       0,
			Notes:          "Signing operation, 100 iterations",
		},
		{
			Component:      "BLS12-381 Operations",
			TestType:       "Cryptographic",
			Nodes:          1,
			FaultTolerance: 0,
			CurveType:      "BLS12-381",
			Duration:       0.622,
			Success:        true,
			MessagesSent:   "N/A",
			MessagesRecv:   "N/A",
			Timeouts:       0,
			Notes:          "Verification operation, 100 iterations",
		},
		{
			Component:      "Secp256k1 Operations",
			TestType:       "Cryptographic",
			Nodes:          1,
			FaultTolerance: 0,
			CurveType:      "Secp256k1",
			Duration:       0.000835,
			Success:        true,
			MessagesSent:   "N/A",
			MessagesRecv:   "N/A",
			Timeouts:       0,
			Notes:          "Signing operation, 100 iterations",
		},
		{
			Component:      "Secp256k1 Operations",
			TestType:       "Cryptographic",
			Nodes:          1,
			FaultTolerance: 0,
			CurveType:      "Secp256k1",
			Duration:       0.000331,
			Success:        true,
			MessagesSent:   "N/A",
			MessagesRecv:   "N/A",
			Timeouts:       0,
			Notes:          "Verification operation, 100 iterations",
		},
		{
			Component:      "Key Generation",
			TestType:       "BLS12-381",
			Nodes:          4,
			FaultTolerance: 1,
			CurveType:      "BLS12-381",
			Duration:       0.287,
			Success:        true,
			MessagesSent:   "N/A",
			MessagesRecv:   "N/A",
			Timeouts:       0,
			Notes:          "Threshold key generation",
		},
		{
			Component:      "Key Generation",
			TestType:       "Secp256k1",
			Nodes:          4,
			FaultTolerance: 1,
			CurveType:      "Secp256k1",
			Duration:       0.953,
			Success:        true,
			MessagesSent:   "N/A",
			MessagesRecv:   "N/A",
			Timeouts:       0,
			Notes:          "Threshold key generation",
		},
	}
	
	// Save results to CSV
	if err := saveToCSV(results, outputFile); err != nil {
		log.Fatalf("Failed to save CSV: %v", err)
	}
	
	// Save results to JSON
	jsonFile := outputFile[:len(outputFile)-4] + ".json"
	if err := saveToJSON(results, jsonFile); err != nil {
		log.Fatalf("Failed to save JSON: %v", err)
	}
	
	fmt.Printf("Detailed performance results saved to %s and %s\n", outputFile, jsonFile)
	
	// Print summary
	fmt.Println("\n=== Performance Summary ===")
	fmt.Printf("Total tests: %d\n", len(results))
	successCount := 0
	for _, result := range results {
		if result.Success {
			successCount++
		}
	}
	fmt.Printf("Successful tests: %d (%.1f%%)\n", successCount, float64(successCount)/float64(len(results))*100)
	
	// Print key findings
	fmt.Println("\n=== Key Findings ===")
	fmt.Println("✅ Threshold Coin Protocol: Working correctly (~500ms)")
	fmt.Println("✅ Component-level tests: 90.9% success rate")
	fmt.Println("✅ Secp256k1 crypto operations: 696x faster signing, 1879x faster verification")
	fmt.Println("❌ Full ADKR Protocol: ACSS timeout issues")
	fmt.Println("📊 Overall: Core components working, integration needs improvement")
}

func saveToCSV(results []DetailedPerformanceResult, filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()
	
	writer := csv.NewWriter(file)
	defer writer.Flush()
	
	// Write header
	header := []string{
		"Component", "Test Type", "Nodes", "Fault Tolerance", "Curve Type",
		"Duration (ms)", "Success", "Messages Sent", "Messages Recv",
		"Timeouts", "Error", "Notes",
	}
	if err := writer.Write(header); err != nil {
		return err
	}
	
	// Write data
	for _, result := range results {
		record := []string{
			result.Component,
			result.TestType,
			strconv.Itoa(result.Nodes),
			strconv.Itoa(result.FaultTolerance),
			result.CurveType,
			strconv.FormatFloat(result.Duration, 'f', 3, 64),
			strconv.FormatBool(result.Success),
			result.MessagesSent,
			result.MessagesRecv,
			strconv.Itoa(result.Timeouts),
			result.Error,
			result.Notes,
		}
		if err := writer.Write(record); err != nil {
			return err
		}
	}
	
	return nil
}

func saveToJSON(results []DetailedPerformanceResult, filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()
	
	encoder := json.NewEncoder(file)
	encoder.SetIndent("", "  ")
	return encoder.Encode(results)
}
